package com.neu.af.dataFilter.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neu.af.dataFilter.entity.User;
import com.neu.af.dataFilter.entity.UserExample;
import com.neu.af.dataFilter.mapper.UserMapper;
import com.neu.af.dataFilter.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("LoginService")
public class LoginServiceImpl implements LoginService {
    @Autowired
    UserMapper loginMapper;

    @Override
    public int insert(User record) {
        if (loginMapper.selectByNameUnique(record.getName()) > 0) {
            return -1;
        }
        return loginMapper.insert(record);
    }

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return loginMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKey(User example) {
        Map<String, Object> data = new HashMap<>();
        data.put("id", example.getId());
        data.put("name", example.getName());
        if (loginMapper.selectByNameUniqueExpectId(data) > 0) {
            return -1;
        }
        return loginMapper.updateByPrimaryKeySelective(example);
    }

    @Override
    public int countByExample(UserExample example) {
        return loginMapper.countByExample(example);
    }

    @Override
    public Map<String, Object> selectByName(String name, int page, int pageSize) {
        Map<String, Object> map = new HashMap<>();
        UserExample UserExample = new UserExample();
        UserExample.Criteria criteria = UserExample.createCriteria();
        if (!name.equals("")) {
            criteria.andNameEqualTo(name);
        }
        PageHelper.startPage(page, pageSize);
        List<User> list = loginMapper.selectByName(name);
        PageInfo pageUser = new PageInfo(list);
        long sum = pageUser.getTotal();
        list = pageUser.getList();
        map.put("user",list);
        map.put("sum",sum);
        return map;
    }

    @Override
    public List<User> selectByNamePassword(String name, String password) {
        UserExample UserExample = new UserExample();
        UserExample.Criteria criteria = UserExample.createCriteria();
        if (name != null) {
            criteria.andNameEqualTo(name);
        }
        if (password != null) {
            criteria.andNameEqualTo(password);
        }
        return loginMapper.selectByExample(UserExample);
    }

    @Override
    public User getLoginInfo(String name, String password) {
        Map<String, Object> data = new HashMap<>();
        data.put("name", name);
        data.put("password", password);
        return loginMapper.selectByNamePassword(data);
    }
}
